﻿using MCMesServer.DBFunctions.DBFuncs;
using MCMesServer.DBFunctions.TransformFuncs;
using MCMesServer.Model;
using MCMesServer.NetConnectFunc;
using MCMesServer.PublicLogInfo;
using MesDAL.DTO;
using MesDAL.DTO.ProcessSheet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MCMesServer.ServerReceiveFunctions.GenerateProducePlan
{
    public class GenerateProducePlanHandlerFunc
    {
        public static void HandleReceiveMsg(ServerModel model, IntPtr connId)
        {
            try
            {
                switch (model.Operation)
                {
                    case Operations.DownloadIncompleteProcessSheet:
                        ReceiveSelectIncompleteProcessSheet(model, connId);
                        break;
                    case Operations.DownloadMachineMessageByProcessSheet:
                        ReceiveDownloadMachineMessageByProcessSheet(model, connId);
                        break;
                    case Operations.DownloadProducePlanByProcessSheet:
                        ReceiveDownloadProducePlanByProcessSheet(model, connId);
                        break;
                    case Operations.UploadNewProducePlan:
                        //ReceiveUploadNewProducePlan(model, connId);
                        New_ReceiveUploadNewProducePlan(model, connId);
                        break;
                    case Operations.DownloadMachineMessage:
                        ReceiveDownloadMachineMessage(model, connId);
                        break;
                    case Operations.DownloadUnfinishProducePlan:
                        ReceiveDownloadUnfinishProducePlan(model, connId);
                        break;
                    case Operations.UploadNewPriority:
                        ReceiveUploadNewPriority(model, connId);
                        break;
                    case Operations.UploadDeleteProducePlan:
                        ReceiveUploadDeleteProducePlan(model, connId);
                        break;
                    case Operations.UploadEditProducePlan:
                        ReceiveUploadEditProducePlan(model, connId);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                PublicLogInfoFunc.RecordManualErrorMessage($"[{model.Step}]发生接收错误，错误信息内容：{model.Message}", ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 查询未完成的工艺单
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveSelectIncompleteProcessSheet(ServerModel model, IntPtr connId)
        {
            try
            {
                List<ProcessSheetDTO> list = await ProcessSheetDBFunc.SelectIncompleteProcessSheet();
                string message = TransformModelFunc<List<ProcessSheetDTO>>.TransformModel2StringFunc(list);
                ServerModel serverModel = new ServerModel()
                {
                    MachineNum = model.MachineNum,
                    Step = model.Step,
                    Message = message,
                    Operation = model.Operation,
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 检索设备信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveDownloadMachineMessageByProcessSheet(ServerModel model, IntPtr connId)
        {
            try
            {
                ProcessSheetDTO dto = TransformModelFunc<ProcessSheetDTO>.TransformString2ModelFunc(model.Message);
                ProduceplanDTO planDto = await ProduceplanDBFunc.SelectProduceplanByProcessSheet(dto);
                string message = "";
                if (planDto is null)
                {
                    ProduceplanDTO newDto = new ProduceplanDTO()
                    {
                        estimated_start = DateTime.Now,
                        estimated_end = DateTime.Now,
                        processSheet = dto
                    };
                    message = TransformModelFunc<ProduceplanDTO>.TransformModel2StringFunc(newDto);
                }
                else
                {
                    planDto.processSheet = dto;
                    message = TransformModelFunc<ProduceplanDTO>.TransformModel2StringFunc(planDto);
                }

                List<MachineInfoDTO> machine_list = await MachineInfoDBFunc.SelectMachineInfoByMachineClass(dto.name);
                message += "$" + TransformModelFunc<List<MachineInfoDTO>>.TransformModel2StringFunc(machine_list);
                ServerModel serverModel = new ServerModel()
                {
                    MachineNum = model.MachineNum,
                    Step = model.Step,
                    Message = message,
                    Operation = model.Operation,
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 添加新的计划表
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveUploadNewProducePlan(ServerModel model, IntPtr connId)
        {
            try
            {
                ProduceplanDTO planDTO = TransformModelFunc<ProduceplanDTO>.TransformString2ModelFunc(model.Message);
                //检索当前设备以及日期下，最近一件计划表
                ProduceplanDTO latestPlanDTO = await ProduceplanDBFunc.SelectLatestPlanWithMachineAndDate(planDTO.machineInfo, planDTO.estimated_start);
                if (latestPlanDTO is null)
                {
                    //当前设备没有计划表
                    planDTO.priority = 1;
                    planDTO.estimated_end = planDTO.estimated_start.AddHours(planDTO.processSheet.estimatedhours);
                    ProduceplanDTO addPlanDTO = await ProduceplanDBFunc.AddNewProduceplanDTO(planDTO);
                    ServerModel serverModel = new ServerModel()
                    {
                        MachineNum = model.MachineNum,
                        Step = model.Step,
                        Operation = model.Operation,
                        Message = TransformModelFunc<ProduceplanDTO>.TransformModel2StringFunc(planDTO)
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                }
                else
                {
                    if (latestPlanDTO.estimated_end <= planDTO.estimated_start)
                    {
                        //之前最新的计划单完成时间，小于当前日期,即当前日期下，没有计划表
                        planDTO.priority = 1;
                        planDTO.estimated_end = planDTO.estimated_start.AddHours(planDTO.processSheet.estimatedhours);
                        ProduceplanDTO addPlanDTO = await ProduceplanDBFunc.AddNewProduceplanDTO(planDTO);
                        ServerModel serverModel = new ServerModel()
                        {
                            MachineNum = model.MachineNum,
                            Step = model.Step,
                            Operation = model.Operation,
                            Message = TransformModelFunc<ProduceplanDTO>.TransformModel2StringFunc(planDTO)
                        };
                        CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                    }
                    else//latestPlanDTO.estimated_end > planDTO.estimated_start
                    {
                        if (latestPlanDTO.estimated_end < planDTO.estimated_start.AddDays(1))
                        {
                            //最新的计划单结束时间在当前日期中
                            if (latestPlanDTO.estimated_start < planDTO.estimated_start)
                            {
                                //最新计划单划为前一日
                                planDTO.priority = 1;
                                planDTO.estimated_start = latestPlanDTO.estimated_end;
                                planDTO.estimated_end = planDTO.estimated_start.AddHours(planDTO.processSheet.estimatedhours);
                                ProduceplanDTO addPlanDTO = await ProduceplanDBFunc.AddNewProduceplanDTO(planDTO);
                                ServerModel serverModel = new ServerModel()
                                {
                                    MachineNum = model.MachineNum,
                                    Step = model.Step,
                                    Operation = model.Operation,
                                    Message = TransformModelFunc<ProduceplanDTO>.TransformModel2StringFunc(planDTO)
                                };
                                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                            }
                            else
                            {
                                //最新计划单在当前日期中
                                planDTO.priority = latestPlanDTO.priority + 1;
                                planDTO.estimated_start = latestPlanDTO.estimated_end;
                                planDTO.estimated_end = planDTO.estimated_start.AddHours(planDTO.processSheet.estimatedhours);
                                ProduceplanDTO addPlanDTO = await ProduceplanDBFunc.AddNewProduceplanDTO(planDTO);
                                ServerModel serverModel = new ServerModel()
                                {
                                    MachineNum = model.MachineNum,
                                    Step = model.Step,
                                    Operation = model.Operation,
                                    Message = TransformModelFunc<ProduceplanDTO>.TransformModel2StringFunc(planDTO)
                                };
                                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                            }
                        }
                        else//latestPlanDTO.estimated_end >= planDTO.estimated_start.AddDays(1)
                        {
                            //当前日期排班已满
                            ServerModel serverModel = new ServerModel()
                            {
                                MachineNum = model.MachineNum,
                                Step = model.Step,
                                Operation = model.Operation,
                                ResCode = ServerResCode.ERR_TodayPlanFull,
                            };
                            CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 通过工序表查询计划单
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveDownloadProducePlanByProcessSheet(ServerModel model, IntPtr connId)
        {
            try
            {
                List<ProcessSheetDTO> processList = TransformModelFunc<List<ProcessSheetDTO>>.TransformString2ModelFunc(model.Message);
                List<ProduceplanDTO> list = new List<ProduceplanDTO>();
                for (int i = 0; i < processList.Count; i++)
                {
                    ProduceplanDTO dto = await ProduceplanDBFunc.SelectProduceplanByProcessSheet(processList[i]);
                    if (dto != null)
                    {
                        dto.processSheet = processList[i];
                        list.Add(dto);
                    }
                }
                ServerModel serverModel = new ServerModel()
                {
                    Step = model.Step,
                    MachineNum = model.MachineNum,
                    Operation = model.Operation,
                    Message = TransformModelFunc<List<ProduceplanDTO>>.TransformModel2StringFunc(list)
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 查询所有设备信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveDownloadMachineMessage(ServerModel model, IntPtr connId)
        {
            try
            {
                List<MachineInfoDTO> machineList = await MachineInfoDBFunc.SelectMachineInfoMessage();
                ServerModel serverModel = new ServerModel()
                {
                    Step = model.Step,
                    MachineNum = model.MachineNum,
                    Operation = model.Operation,
                    Message = TransformModelFunc<List<MachineInfoDTO>>.TransformModel2StringFunc(machineList)
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 检索尚未完成的计划单
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveDownloadUnfinishProducePlan(ServerModel model, IntPtr connId)
        {
            try
            {
                List<ProduceplanDTO> unfinishList = await ProduceplanDBFunc.SelectAllUnFinishProducePLan();
                ServerModel serverModel = new ServerModel()
                {
                    Step = model.Step,
                    MachineNum = model.MachineNum,
                    Operation = model.Operation,
                    Message = TransformModelFunc<List<ProduceplanDTO>>.TransformModel2StringFunc(unfinishList)
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 上传修改后的新的优先级
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveUploadNewPriority(ServerModel model, IntPtr connId)
        {
            try
            {
                List<ProduceplanDTO> needEditList = TransformModelFunc<List<ProduceplanDTO>>.TransformString2ModelFunc(model.Message);
                List<ProduceplanDTO> machineProducePlanList = await ProduceplanDBFunc.EditIncreasePriority(needEditList);
                ServerModel serverModel = new ServerModel()
                {
                    Step = model.Step,
                    MachineNum = model.MachineNum,
                    Operation = model.Operation,
                    Message = TransformModelFunc<List<ProduceplanDTO>>.TransformModel2StringFunc(machineProducePlanList)
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 接收处理删除已有的计划单指令
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveUploadDeleteProducePlan(ServerModel model, IntPtr connId)
        {
            try
            {
                ProduceplanDTO planDTO = TransformModelFunc<ProduceplanDTO>.TransformString2ModelFunc(model.Message);
                List<ProduceplanDTO> oldList = await ProduceplanDBFunc.SelectProduceplanAfterDate(planDTO.estimated_start.Date);
                bool isDelete = await ProduceplanDBFunc.DeleteProducePlan(planDTO);
                if (isDelete)
                {
                    List<ProduceplanDTO> list = await SelectUnFinishProducePlanWithMachine(planDTO.machineInfo.machine_num);
                    List<ProduceplanDTO> arrangeList = ArrangeDateSort(list);
                    List<ProduceplanDTO> resList = await CompareProduceplanExchange(list, arrangeList);
                    string msg = TransformModelFunc<List<ProduceplanDTO>>.TransformModel2StringFunc(resList);

                    ServerModel serverModel = new ServerModel()
                    {
                        Step = model.Step,
                        MachineNum = model.MachineNum,
                        Operation = model.Operation,
                        ResCode = ServerResCode.OPE_DeletePlanSuccess,
                        Message = msg
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                }
                else
                {
                    ServerModel serverModel = new ServerModel()
                    {
                        Step = model.Step,
                        MachineNum = model.MachineNum,
                        Operation = model.Operation,
                        ResCode = ServerResCode.ERR_DeletePlanFail
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                }
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 接收需要编辑的排产单
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveUploadEditProducePlan(ServerModel model, IntPtr connId)
        {
            try
            {
                ProduceplanDTO dto = TransformModelFunc<ProduceplanDTO>.TransformString2ModelFunc(model.Message);
                List<ProduceplanDTO> unfinishList = await SelectUnFinishProducePlanWithMachine(dto.machineInfo.machine_num);
                List<ProduceplanDTO> newList = new List<ProduceplanDTO>();
                foreach (var item in unfinishList)
                {
                    newList.Add(item);
                }
                int index = newList.FindIndex(x => x.id == dto.id);
                if (index < 0)
                {
                    ServerModel serverModel = new ServerModel()
                    {
                        MachineNum = model.MachineNum,
                        Step = model.Step,
                        Operation = model.Operation,
                        ResCode = ServerResCode.ERR_NullProducePlanInDB,
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                }
                else
                {
                    newList[index] = dto;
                    newList = ArrangeProducePlanToSort(newList);
                    List<ProduceplanDTO> result = await CompareProduceplanExchange(unfinishList, newList);
                    ServerModel serverModel = new ServerModel()
                    {
                        Step = model.Step,
                        MachineNum = model.MachineNum,
                        Operation = model.Operation,
                        Message = TransformModelFunc<List<ProduceplanDTO>>.TransformModel2StringFunc(result),
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                }
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        #region 新方法
        public async static void New_ReceiveUploadNewProducePlan(ServerModel model, IntPtr connId)
        {
            try
            {
                ProduceplanDTO addNewPlan = TransformModelFunc<ProduceplanDTO>.TransformString2ModelFunc(model.Message);//需要添加插入的新
                List<ProduceplanDTO> list = await SelectUnFinishProducePlanWithMachine(addNewPlan.machineInfo.machine_num);

                List<ProduceplanDTO> resList = new List<ProduceplanDTO>();
                if (list.Count > 0)
                {
                    resList = ArrangeAddNewProducePlanInList(list, addNewPlan);
                }
                else
                {
                    resList.Add(addNewPlan);
                }
                resList = ArrangeProducePlanToSort(resList);
                List<ProduceplanDTO> resultList = await CompareProduceplanExchange(list, resList);
                ServerModel serverModel = new ServerModel()
                {
                    Step = model.Step,
                    MachineNum = model.MachineNum,
                    Operation = model.Operation,
                    Message = TransformModelFunc<List<ProduceplanDTO>>.TransformModel2StringFunc(resultList)
                };
                CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        #endregion

        #region 公共整理方法
        /// <summary>
        /// 检索某台设备中未完成的计划单
        /// </summary>
        private async static Task<List<ProduceplanDTO>> SelectUnFinishProducePlanWithMachine(string machineNum)
        {
            List<ProduceplanDTO> produceList = await ProduceplanDBFunc.SelectUnFinishProducePlanWithMachine(machineNum);
            return produceList;
        }

        /// <summary>
        /// 检索某台设备中未完成的计划单
        /// </summary>
        private async static Task<List<ProduceplanDTO>> SelectUnFinishProducePlanWithMachine(int machineId)
        {
            List<ProduceplanDTO> produceList = await ProduceplanDBFunc.SelectUnFinishProducePlanWithMachineId(machineId);
            return produceList;
        }

        /// <summary>
        /// 将已有的几乎单排序，排序优先级、预计开始结束时间
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private static List<ProduceplanDTO> ArrangeProducePlanToSort(List<ProduceplanDTO> list)
        {
            List<ProduceplanDTO> resList = new List<ProduceplanDTO>();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == 0)
                {
                    int newPriority = i + 1;
                    ProduceplanDTO dto = new ProduceplanDTO()
                    {
                        id = list[i].id,
                        estimated_start = list[i].estimated_start,
                        estimated_end = list[i].estimated_end,
                        processSheet = list[i].processSheet,
                        priority = newPriority,
                        machineInfo = list[i].machineInfo,
                        discontinuous_date = list[i].discontinuous_date,
                    };
                    resList.Add(dto);
                }
                else
                {
                    int newPriority = i + 1;
                    ProduceplanDTO dto = new ProduceplanDTO()
                    {
                        id = list[i].id,
                        estimated_end = list[i].estimated_end,
                        estimated_start = list[i].estimated_start,
                        processSheet = list[i].processSheet,
                        machineInfo = list[i].machineInfo,
                        priority = newPriority,
                        discontinuous_date = list[i].discontinuous_date,
                    };
                    if (resList[resList.Count - 1].estimated_end != dto.estimated_start && !dto.discontinuous_date)
                    {
                        dto.estimated_start = resList[resList.Count - 1].estimated_end;
                        dto.estimated_end = dto.estimated_start.AddHours(dto.processSheet.estimatedhours);
                    }
                    resList.Add(dto);
                }
            }
            return resList;
        }

        /// <summary>
        /// 向已有的计划单列表中加入新的计划单
        /// </summary>
        /// <param name="list"></param>
        private static List<ProduceplanDTO> ArrangeAddNewProducePlanInList(List<ProduceplanDTO> list, ProduceplanDTO addNewPlan)
        {
            DateTime addTime = addNewPlan.estimated_start;
            List<ProduceplanDTO> resList = new List<ProduceplanDTO>();
            foreach (var item in list)
            {
                resList.Add(item);
            }
            int lastIndex = resList.FindLastIndex(x => x.estimated_start.Date == addNewPlan.estimated_start.Date);
            if (lastIndex < 0)//没有当前日期
            {
                if (resList[0].estimated_start > addTime)
                {
                    if (DateTime.Now.Date == addTime.Date)//当天日期
                    {
                        addNewPlan.estimated_start = DateTime.Now.Date;
                        addNewPlan.estimated_end = addNewPlan.estimated_start.AddHours(addNewPlan.processSheet.estimatedhours);
                    }
                    resList.Insert(0, addNewPlan);
                }
                else if (resList[resList.Count - 1].estimated_start < addTime)
                {
                    resList.Add(addNewPlan);
                }
            }
            else
            {
                resList.Insert(lastIndex + 1, addNewPlan);
            }
            return resList;
        }

        /// <summary>
        /// 比较最新的整理后的计划单以及老的计划单，更新数据库信息
        /// </summary>
        /// <param name="oldList"></param>
        /// <param name="newList"></param>
        /// <returns></returns>
        private async static Task<List<ProduceplanDTO>> CompareProduceplanExchange(List<ProduceplanDTO> oldList, List<ProduceplanDTO> newList)
        {
            List<ProduceplanDTO> needEditList = new List<ProduceplanDTO>();
            List<ProduceplanDTO> resultList = new List<ProduceplanDTO>();
            foreach (var item in newList)
            {
                int index = oldList.FindIndex(x => x.processSheet.id == item.processSheet.id);
                if (index < 0)
                {
                    //新添加的计划单
                    ProduceplanDTO dto = await ProduceplanDBFunc.AddNewProduceplanDTO(item);
                    resultList.Add(dto);
                }
                else
                {
                    if (item.priority == oldList[index].priority && item.estimated_start == oldList[index].estimated_start
                        && item.estimated_end == oldList[index].estimated_end && item.discontinuous_date == oldList[index].discontinuous_date)
                    {
                        //无需更改
                        continue;
                    }
                    else
                    {
                        //需要在数据库内更改
                        needEditList.Add(item);
                    }
                }
            }
            if (needEditList.Count > 0)
            {
                List<ProduceplanDTO> editResultList = await ProduceplanDBFunc.EditProducePlanList(needEditList);
                resultList.AddRange(editResultList);
            }
            if (resultList.Count > 0)
            {
                for (int i = 0; i < resultList.Count; i++)
                {
                    if (resultList[i].processSheet.workpiece is null)
                    {
                        resultList[i].processSheet.workpiece = await WorkPieceDBFunc.SelectWorkPieceByProcessId(resultList[i].processSheet.id);
                    }
                    else
                    {
                        if (resultList[i].processSheet.workpiece.name is null || resultList[i].processSheet.workpiece.number is null || resultList[i].processSheet.workpiece.order is null)
                        {
                            resultList[i].processSheet.workpiece = await WorkPieceDBFunc.SelectWorkPieceByWorkpieceId(resultList[i].processSheet.workpiece.id);
                        }
                    }
                }
            }
            return resultList;

        }

        /// <summary>
        /// 整理当前日期之后的计划单
        /// </summary>
        /// <param name="date"></param>
        private async static Task<List<ProduceplanDTO>> ArrangeProducePlanAfterDate(DateTime date)
        {
            List<ProduceplanDTO> list = await ProduceplanDBFunc.SelectProduceplanAfterDate(date);//检索修改日期之后所有未完成的计划单

            //筛选出当天日期以及之后日期的排产计划单
            //DateTime tomorrow = date.AddDays(1);
            //List<ProduceplanDTO> todayList = list.Where(x => x.estimated_start < tomorrow).OrderBy(x => x.estimated_start).ToList();
            //List<ProduceplanDTO> tomorrowList = list.Where(x => x.estimated_start >= tomorrow).OrderBy(x => x.estimated_start).ToList();

            List<ProduceplanDTO> arrangeTodayList = ArrangeDateSort(list);
            return arrangeTodayList;
        }

        private static List<ProduceplanDTO> ArrangeDateSort(List<ProduceplanDTO> list)
        {
            List<ProduceplanDTO> resList = new List<ProduceplanDTO>();
            for (int i = 0; i < list.Count; i++)
            {
                ProduceplanDTO dto = new ProduceplanDTO()
                {
                    id = list[i].id,
                    machineInfo = list[i].machineInfo,
                    processSheet = list[i].processSheet,
                    priority = resList.Count + 1,
                    estimated_start = list[i].estimated_start,
                    estimated_end = list[i].estimated_end,
                    discontinuous_date = list[i].discontinuous_date
                };
                if (i == 0)
                {
                    resList.Add(dto);
                }
                else
                {
                    if (list[i].discontinuous_date)
                    {
                        //当前任务日期工作时间不需要连贯
                        resList.Add(dto);
                    }
                    else
                    {
                        //当前任务需要连贯
                        if (list[i].estimated_start == resList[i - 1].estimated_end)
                        {
                            resList.Add(dto);
                        }
                        else
                        {
                            ProduceplanDTO adddto = new ProduceplanDTO()
                            {
                                id = list[i].id,
                                machineInfo = list[i].machineInfo,
                                processSheet = list[i].processSheet,
                                priority = resList.Capacity + 1,
                                estimated_start = resList.LastOrDefault().estimated_end,
                            };
                            adddto.estimated_end = adddto.estimated_start.AddHours(dto.processSheet.estimatedhours);
                            resList.Add(adddto);
                        }
                    }
                }
            }
            return resList;
        }
        #endregion
    }
}
